package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * 缓存工具类
 * 缓存穿透
 * 缓存击穿（逻辑过期）
 */
@Component
public class CacheClient {
    private final StringRedisTemplate stringRedisTemplate;

    private CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 该方法提供存入redis的string结构
     *
     * @param key
     * @param val
     * @param time
     * @param timeUnit
     */
    public void set(String key, Object val, Long time, TimeUnit timeUnit) {
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(val), time, timeUnit);
    }

    /**
     * 该方法提供存入redis的string结构,并为该对象添加逻辑过期字段,无过期时间，只有逻辑过期字段
     *
     * @param key
     * @param val
     * @param time
     * @param timeUnit
     */
    public void setWithLogicalExpire(String key, Object val, Long time, TimeUnit timeUnit) {
        RedisData redisData = new RedisData();
        redisData.setData(val);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(timeUnit.toSeconds(time)));
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    /**
     * 缓存穿透 数据库没数据，导致一直访问数据库，压力大，恶意攻击
     * <p>
     * 1.先去redis查，redis数据不为null，不为空串，直接返回数据
     * 2.1如果查到是空串，说明不是第一次来，直接返回null
     * 2.2如果没查到空串，说明第一次来，
     * 2.2.1查数据库，查到放数据入redis，返回数据
     * 2.2.2 没查到放空串到redis，返回null
     *
     * @param keyPrefix  key的前缀
     * @param id         缓存对象id
     * @param type       缓存对象类型
     * @param dbFallBack 函数式编程，根据id查询数据库
     * @param time       过期时间
     * @param timeUnit   时间单位
     * @param <R>        对象 类型
     * @param <ID>       id 类型
     * @return
     */

    public <R, ID> R queryWithCachePenetration(
            String keyPrefix,
            ID id,
            Class<R> type,
            Function<ID, R> dbFallBack,
            Long time,
            TimeUnit timeUnit) {
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(json)) {
            return JSONUtil.toBean(json, type);
        }
        if (json != null) {//空串走这个if
            return null;
        }
        R r = dbFallBack.apply(id);
        if (r == null) {
            this.set(key, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        this.set(key, r, time, timeUnit);
        return r;
    }

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    /**
     * 缓存击穿 逻辑过期
     *
     * @param keyPrefix
     * @param id
     * @param type
     * @param dbFallBack
     * @param time
     * @param timeUnit
     * @param <R>
     * @param <ID>
     * @return
     */
    public <R, ID> R queryWithLogicalExpire(
            String keyPrefix,
            ID id,
            Class<R> type,
            Function<ID, R> dbFallBack,
            Long time,
            TimeUnit timeUnit) {

        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isBlank(json)) {
            // 缓存未命中返回空
            return null;
        }
        // 存在，判断过期时间
        // 未过期，返回
        // 过期，获取互斥锁，成功开启线程缓存重建返回，失败返回
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);

        R r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
        LocalDateTime expireTime = redisData.getExpireTime();
        if (expireTime.isAfter(LocalDateTime.now())) {
            // 未过期，返回
            return r;
        }
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        // 获取锁成功也要doublecheck
        boolean b = tryLock(lockKey);
        if (b) {
            CACHE_REBUILD_EXECUTOR.submit(
                    () -> {
                        // 重建缓存
                        try {
                            // 查数据库，写redis
                            R apply = dbFallBack.apply(id);
                            this.setWithLogicalExpire(key, apply, time, timeUnit);
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        } finally {
                            this.unLock(lockKey);
                        }
                    });
        }
        return r;//返回旧值
    }

    private boolean tryLock(String key) {
        Boolean aBoolean =
                stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(aBoolean); // 预防空指针,空指针返回false
    }

    private void unLock(String key) {
        Boolean delete = stringRedisTemplate.delete(key);
    }
}
